//
//  WebViewControler.m
//  SDK_Demo
//
//  Created by dyj on 16/7/18.
//  Copyright © 2016年 dyj. All rights reserved.
//

#import "JZMWebViewControler.h"
#import "webTool.h"
#import "NSData+JZMBase64.h"
#import "NSData+AES.h"
#import <Photos/Photos.h>
#import "WXApi.h"
#import "JZMConfigureHeader.h"
NSString * const WEBKEY = @"66af8593f42b01b3ee815ad8be980e3c";
NSString * const WEBIV = @"04c52bed86e11f9e";
@interface JZMWebViewControler()<UIWebViewDelegate,UIAlertViewDelegate>{
    CABasicAnimation *animation;
    CALayer *dotLayer;
    UIView *bgView;
}
@property(nonatomic,strong) UIWebView *webview;
@property(nonatomic,strong) UIImageView *imgView;
@property(nonatomic,strong) UIAlertView *jftAlertView;
@end
@implementation JZMWebViewControler
- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self.navigationController.navigationBar setTranslucent:NO];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelDidClick)];
    [self.navigationItem setLeftBarButtonItem:leftButton];    
    self.webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0,JZMSCREEN_WIDTH, JZMSCREEN_HEIGHT-64)];
    self.webview.scalesPageToFit = YES;
    self.webview.delegate = self;
//    self.webUrl = [self.webUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
    [self.view addSubview:self.webview];
    bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, JZMSCREEN_WIDTH, JZMSCREEN_HEIGHT)];
    bgView.backgroundColor = [UIColor clearColor];
    [self addAnimation];
    [self addRoatation];
    bgView.hidden = YES;
    if (@available(iOS 11.0, *)) {
        self.webview.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

- (UIAlertView *)jftAlertView{
    if (!_jftAlertView) {
        _jftAlertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    }
    return _jftAlertView;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
     NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    switch (buttonIndex) {
        case 0:
            break;
        case 1:
            if([[UIApplication sharedApplication] canOpenURL:url]) {
                NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
            }
            break;
        default:
            break;
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
   NSString *urlString = [[request URL] absoluteString];
    if ([urlString hasPrefix:@"weixin"]) {
        self.openComplete(YES, urlString);
        [self dismiss];
        return YES;
    }
   urlString=[urlString stringByRemovingPercentEncoding];
   NSArray *urlComps = [urlString componentsSeparatedByString:@":||"];
    if([urlComps count] && [[urlComps objectAtIndex:0] isEqualToString:@"objc"])
    {
        if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:(NSString *)[urlComps objectAtIndex:1]]])
        {
            [self getParam1:[urlComps objectAtIndex:1]];
        }
    }else if(([urlComps count] && [[urlComps objectAtIndex:0] isEqualToString:@"jhmobiel"])){
        NSError *err =nil;
        [NSData dataFromBase64String:[urlComps objectAtIndex:1]];
        NSData *de_data = [[NSData dataFromBase64String:[urlComps objectAtIndex:1]] AES256DecryptWithKey:WEBKEY iv:WEBIV];
        NSDictionary *dic= [NSJSONSerialization JSONObjectWithData:de_data options:NSJSONReadingMutableLeaves error:&err];
        if ([dic[@"method"] isEqualToString:@"WeiXinFenXiang"]) {
            NSDictionary *paramList = [dic objectForKey:@"paramList"];
            if (![[paramList objectForKey:@"url"] isEqualToString:@""]) {
                NSString *urlString = [paramList objectForKey:@"url"];
                NSString *myUrl = [urlString stringByRemovingPercentEncoding];
                if([[paramList objectForKey:@"type"] intValue] == 1){
                    NSRange range = [myUrl rangeOfString:@"weixin"];
                    NSString *str = [myUrl substringFromIndex:range.location];
                    self.imgView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, JZMSCREEN_WIDTH/2.0, JZMSCREEN_WIDTH/2.0)];
                    [self erweimaWithString:str];
                    [self sharedActio:self.imgView.image];
                }else if ([[paramList objectForKey:@"type"] intValue] == 4){
                    self.imgView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, JZMSCREEN_WIDTH/2.0, JZMSCREEN_WIDTH/2.0)];
                    [self erweimaWithString:myUrl];
                    [self sharedActio:self.imgView.image];
                }else if([[paramList objectForKey:@"type"] intValue] == 2&&![[paramList objectForKey:@"appid"] isEqualToString:@""]){//type = 2 是公众号直接拉起支付，已经没有了
                    self.begainOpen(YES);
                    [self Invoke:myUrl andAppid:[paramList objectForKey:@"appid"]];
                }else if([[paramList objectForKey:@"type"] intValue] == 3&&![[paramList objectForKey:@"url"] isEqualToString:@""]){//type = 3 扫一扫支付
                        self.begainOpen(YES);
                        [self scanQRCodePayWithurl:[paramList objectForKey:@"url"]];
                    }
            }else {
                [self.jftAlertView setMessage:@"未获取到二维码"];
                [self.jftAlertView show];
                self.openComplete(0, @"未获取到二维码或支付链接");
            }
        }
    }
    return YES;
}

- (void)scanQRCodePayWithurl:(NSString *)urlString{
    self.imgView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, JZMSCREEN_WIDTH/2.0, JZMSCREEN_WIDTH/2.0)];
    [self erweimaWithString:[[urlString stringByRemovingPercentEncoding] stringByRemovingPercentEncoding]];
    [self saveImage2Photo:self.imgView.image];
}

- (void)sharedActio:(UIImage*)htmlImage{
    [self registerApp];
    if ([self registerApp]) {
        WXMediaMessage *message = [WXMediaMessage message];
        WXImageObject *ext = [WXImageObject object];
        NSData* dataImg = UIImageJPEGRepresentation(htmlImage, 1.0);
        ext.imageData = dataImg;
        message.mediaObject = ext;
        message.messageExt = @"AAA";
        message.messageAction = @"<action>dotalist</action>";
        message.mediaTagName = @"WECHAT_TAG_JUMP_SHOWRANK";
        [message setThumbImage:htmlImage];
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc]init];
        req.scene = 0;
        req.bText = NO;
        req.message=message;
        BOOL mm = [WXApi sendReq:req];
        self.openComplete(mm,@"");
        if (mm) {
            [self dismiss];
        }else
            NSLog(@"NO");
    }
}

- (void)Invoke:(NSString *)htmlJson andAppid:(NSString *)appid{
    [WXApi registerApp:appid];//注册appID
    OpenWebviewReq *webViewReq = [[OpenWebviewReq alloc]init];
    webViewReq.url = htmlJson;
    [WXApi sendReq:webViewReq];
}

- (BOOL)registerApp{
    UInt64 typeFlag = MMAPP_SUPPORT_TEXT | MMAPP_SUPPORT_PICTURE | MMAPP_SUPPORT_LOCATION | MMAPP_SUPPORT_VIDEO |MMAPP_SUPPORT_AUDIO | MMAPP_SUPPORT_WEBPAGE | MMAPP_SUPPORT_DOC | MMAPP_SUPPORT_DOCX | MMAPP_SUPPORT_PPT | MMAPP_SUPPORT_PPTX | MMAPP_SUPPORT_XLS | MMAPP_SUPPORT_XLSX | MMAPP_SUPPORT_PDF;
    [WXApi registerAppSupportContentFlag:typeFlag];
    if (!self.weichatAppid||[self.weichatAppid isEqualToString:@""]) {
        self.weichatAppid = @"wx300fddeeab22db85";
        NSLog(@"添加您的appid到支付模型");
    }
    return [WXApi registerApp:self.weichatAppid];
}

- (void)saveImage2Photo:(UIImage *)img {
    if ([self isCanUsePhotos]) {
        UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
    }else{
        self.jftAlertView.message = @"没有权限访问相册，请前往设置页面设置";
        [self.jftAlertView addButtonWithTitle:@"确定"];
        [_jftAlertView show];
    }
}

- (BOOL)isCanUsePhotos {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted ||
        status == PHAuthorizationStatusDenied) {
        //无权限
        return NO;
    }else
        return YES;
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error == nil) {
        NSLog(@"保存成功");
       BOOL m= [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"weixin://scanqrcode"]];
        if (m) {
            [self dismiss];
            self.openComplete(m, @"weixin://scanqrcode");
        }
    }else{
        NSLog(@"%@",error);
    }
}

-(void)erweimaWithString:(NSString*)string
{
    //二维码滤镜
    CIFilter *filter=[CIFilter filterWithName:@"CIQRCodeGenerator"];
    //恢复滤镜的默认属性
    [filter setDefaults];
    //将字符串转换成NSData
    NSData *data=[string dataUsingEncoding:NSUTF8StringEncoding];
    //通过KVO设置滤镜inputmessage数据
    [filter setValue:data forKey:@"inputMessage"];
    [filter setValue:@"H" forKey:@"inputCorrectionLevel"];
    //获得滤镜输出的图像
    CIImage *outputImage=[filter outputImage];
    //将CIImage转换成UIImage,并放大显示
    self.imgView.image=[self createNonInterpolatedUIImageFormCIImage:outputImage withSize:100.0];
    //如果还想加上阴影，就在ImageView的Layer上使用下面代码添加阴影
    self.imgView.layer.shadowOffset=CGSizeMake(0, 0.5);//设置阴影的偏移量
    self.imgView.layer.shadowRadius=1;//设置阴影的半径
    self.imgView.layer.shadowColor=[UIColor blackColor].CGColor;//设置阴影的颜色为黑色
    self.imgView.layer.shadowOpacity=0.3;
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    UIImage *reImage = [UIImage imageWithCGImage:scaledImage];
    CGImageRelease(scaledImage);
    CGContextRelease(bitmapRef);
    CGColorSpaceRelease(cs);
    CGImageRelease(bitmapImage);
    return reImage;
}

- (void)dealloc{
    _jftAlertView.delegate =nil;
    _jftAlertView =nil;
}
//- (void)addCashierFunc:(NSString *)imgUrl{
//    WXMediaMessage *message = [WXMediaMessage message];
//    NSData * dataImg = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
//    
//    //    NSData *data = UIImageJPEGRepresentation(self.qrcodeImage.image, 1);
//    WXImageObject *ext = [WXImageObject object];
//    //    NSData * imgData = [self checkThumbImageSize:data];
//    ext.imageData = dataImg;
//    message.mediaObject = ext;
//    //    message.title = self.nstrScanText;
//    //    NSLog(@"%@",self.nstrPayInfo);
//    message.messageExt = @"AAA";
//    message.messageAction = @"<action>dotalist</action>";
//    message.mediaTagName = @"WECHAT_TAG_JUMP_SHOWRANK";
//    [message setThumbImage:[UIImage imageWithData:dataImg]];
//    SendMessageToWXReq* req = [[SendMessageToWXReq alloc]init];
//    req.scene = 0;
//    req.bText = NO;
//    req.message=message;
//    BOOL mm = [WXApi sendReq:req];
//    if (mm) {
//        NSLog(@"yes");
//        
//    }else
//        NSLog(@"NO");
//    
//}

-(void)getParam1:(NSString*)str1
{
    if (str1) {
        bgView.hidden = NO;
        [dotLayer addAnimation:animation forKey:nil];
        webTool *tool=[webTool sharedInstance];
        [tool gety:str1];
        tool.block=^(NSString *success){
            bgView.hidden =YES;
            [self dismiss];
        };
    }
}

- (void)cancelDidClick{
    [self dismissViewControllerAnimated:YES completion:^{
        self.didClickCancel();
    }];
}

- (void)dismiss{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)addAnimation
{
    CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
    replicatorLayer.bounds          = CGRectMake(0, 0, 100, 100);
    replicatorLayer.cornerRadius    = 10.0;
    replicatorLayer.position        =  self.view.center;
    replicatorLayer.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.2].CGColor;
    [bgView.layer addSublayer:replicatorLayer];
    dotLayer  = [CALayer layer];
    dotLayer.bounds = CGRectMake(0, 0, 15, 15);
    dotLayer.position = CGPointMake(15, replicatorLayer.frame.size.height/2 );
    dotLayer.backgroundColor = [UIColor blackColor].CGColor;
    dotLayer.cornerRadius    = 7.5;
    [replicatorLayer addSublayer:dotLayer];
    replicatorLayer.instanceCount = 3;
    replicatorLayer.instanceTransform = CATransform3DMakeTranslation(replicatorLayer.frame.size.width/3, 0, 0);
    animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation.duration    = 1.0;
    animation.fromValue   = @1;
    animation.toValue     = @0.1;
    animation.repeatCount = MAXFLOAT;
    replicatorLayer.instanceDelay = 1.0/3;
    [self.view.layer addSublayer:bgView.layer];
}

- (void)addRoatation{
    CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
    replicatorLayer.bounds = CGRectMake(0, 0, 100, 100);
    replicatorLayer.cornerRadius = 10.0;
    replicatorLayer.position = self.view.center;
    replicatorLayer.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.2].CGColor;
    CALayer *dot = [CALayer layer];
    dot.bounds = CGRectMake(0, 0, 10, 10);
    dot.position = CGPointMake(50, 30);
    CGFloat angel = 2*M_PI/15;
    CFTimeInterval duration = 1.5;
    replicatorLayer.repeatDuration = duration;
    replicatorLayer.instanceCount = 15;
    replicatorLayer.instanceTransform = CATransform3DMakeRotation(angel, 0, 0, 1);
    [replicatorLayer addSublayer:dot];
    CABasicAnimation *shrinkAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    shrinkAnimation.fromValue = @1;
    shrinkAnimation.toValue = @0.1;
    shrinkAnimation.repeatDuration = INFINITY;
    [dot addAnimation:shrinkAnimation forKey:nil];
    replicatorLayer.instanceDelay = duration/15;
    dot.transform = CATransform3DMakeTranslation(0.1, 0.1, 0.1);
    [self.view.layer addSublayer:replicatorLayer];
}

@end
